/**
 * Created by Dell on 2017/4/24.
 */
'use strict';
var pg = require('../lib/pgClient');
const log = require('log4js').getLogger("models/admin");
const async = require('async');
let sqlStart = "START TRANSACTION;";
let sqlRollback = "ROLLBACK;";
let sqlCommit = "COMMIT;";
/**
 * app激活已有账号
 * @param params
 * @param callback
 */
const active_sql1 = 'SELECT * FROM admin WHERE mobile = $1 AND status = $2';
const active_sql2 = 'UPDATE admin SET password = $1, status = $2 WHERE mobile = $3';
exports.active_admin_b = function(params, args, callback){
    const params1 = [
        args.mobile,
        3
    ];
    pg.query(active_sql1, params1,function(err, result){
        if(err){
            callback (err,null);
        }else if(result.rowCount == 0){//未注册
            callback (err,null);
        }else if(result.rows[0].password){//账号已经激活
            callback (err,'exit');
        }else {//执行激活
            pg.query(active_sql2, params, function(err,result){
                if(err){
                    callback (err,null);
                }else {
                    callback (err,result);
                }
            })
        }
    });
};
/**
 *前台用户登陆
 * @param params//数组，传的条件   args.mobile,联系方式args.password
 * @param args传的
 * @param callback
 */
const log_in_sql1 = 'SELECT * FROM admin WHERE mobile = $1';//查询用户
const log_in_sql2 = 'UPDATE admin SET lasttime = $1 WHERE mobile = $2 RETURNING *';//编辑上次登录时间
exports.log_in = function(params, args, callback) {
    const log_in_params1 = [args.mobile];
    const log_in_params2 = [
        new Date(),
        args.mobile
    ]
    pg.query(log_in_sql1, log_in_params1, function (err, result) {//执行查询
        if (err) {
            return callback(err, null);
        }
        else if(result.rowCount == 0) {//没有用户
            return  callback(err,null);
        }else if(result.rows[0].password == params[0]){//对比密码
            pg.query(log_in_sql2, log_in_params2, function(err, result){//执行修改上次登录时间
                if(err){
                    callback (err, null);
                }else if (result.roeCount==0){//编辑失败
                    callback (err, 'fail');
                }else {
                    return  callback(err,result);
                }
            });
        }else if(!result.rows[0].password||result.rows[0].status == 3){//用户未激活
            return  callback(err,'wrong_status');
        }else if(result.rows[0].password != params[0]){
            return callback(err,'wrong_password');//密码错误
        }

    });
};
/**
 * 后台添加系统用户
 * @param params
 * @param args
 * @param callback
 */
const add_sql1 = 'SELECT id FROM admin WHERE mobile = $1';
const add_sql2 = 'SELECT id FROM admin WHERE email = $1';
const add_sql3 = 'INSERT INTO admin ( adminname, mobile, role, email, "desc", headurl, createtime, status) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)';
exports.add_admin = function(params, args, callback){
    const params1 = [
        args.mobile
    ];
    const params2 = [
        args.email
    ];
  pg.query(add_sql1, params1, function(err,result){//查找手机号
      if(err){
          callback (err, null);
      }else if(result.rowCount > 0){
          callback (err,'exit_mobile');//手机号已经注册
      }else{
          pg.query(add_sql2, params2, function(err,result){//查询邮箱
              if(err){
                  callback(err,null);
              }else if(result.rowCount > 0){
                  callback(err,'exit_email');//邮箱已经注册
              }else {
                  pg.query(add_sql3, params, function(err,result){//执行添加用户操作
                      if(err){
                          callback (err,null)
                      }else {
                          callback (err, result);
                      }
                  });
              }
          });
      }
  });
};
/**
 * 后台运营人员列表
 * @param params//查询条件
 * @param callback
 */
exports.list_b = function(params, args, callback){
    let sql = 'SELECT id, adminname, mobile, role, email, status, createtime, lasttime, headurl FROM admin WHERE 1=1';//只有分页操作，根据差个你见时间倒序排列
    let number = 1;
    if(args.status){//状态搜索
        sql += ' AND status = $'+number;
        number++;
    };
    if(args.keyword){//关键字搜索
        sql += ' AND (adminname like $'+number+' OR mobile like $'+number+' OR email like $'+number+' OR "desc" like $'+number+')';
        number++;
    };
    sql +=' ORDER BY createtime DESC LIMIT $'+number+' OFFSET $'+(number+1);
    pg.query(sql, params, function(err, result){//执行查询操作
        if(err){
            callback (err, null);//报错
        }else{
            callback (err, result);//有查询到的结果
        }
    });
};
/**
 * 后台运营人员数据统计
 * @type {string}
 */
exports.count_b = function(params, args, callback){
    let sql = 'SELECT count(*) FROM admin WHERE 1=1';//统计运营人员
    let number = 1;
    if(args.status){//状态搜索
        sql += ' AND status = $'+number;
        number++;
    };
    if(args.keyword){//关键字搜索
        sql += ' AND (adminname like $'+number+' OR mobile like $'+number+' OR email like $'+number+' OR "desc" like $'+number+')';
        number++;
    };
    pg.query(sql, params, function(err, result){//执行统计操作
        if(err){
            callback (err, null);//报错
        }else if(result.rowCount==0){
            callback (err, null);//执行失败
        }else {
            callback (err,result.rows[0].count)//摘取统计的数据
        }
    });
};
/**
 * 后台批量编辑用户状态
 * @param args传递的信息
 * @param callback
 */
exports.upd_status = function(args, callback){
    let ids = args.ids;//ids 是数组
    var theids = "'"+ids.join("','")+"'";//将数组ids整理成字符串
    const upd_sql1 = 'UPDATE admin SET status = $1 WHERE id IN ('+theids+') AND status = $2';//修改id在传进来的id里的所有的用户状态
    const upd_sql2 = 'UPDATE admin SET status = $1 WHERE id IN ('+theids+') AND status != $2';//修改id在传进来的id里的所有的用户状态
    const params = [
        args.status,
        3//未激活的不修改
    ];
    pg.query(upd_sql1, params, function(err, result){//执行查询sql语句
        if(err){
            callback (err,null);//报错
        }else if(result.rowCount==0) {//没有未激活状态用户
            pg.query(upd_sql2, params, function(err, result){//执行编辑sql语句
                if(err){
                    callback (err,null);//报错
                }else {
                    callback (err,result);//返回信息
                }
            })
        }else {
            callback (err,'fail');//有未激活的状态的用户
        }
    })
};
/**
 * 后台系统管理员编辑其他心痛人员的基本信息
 * @param params
 * @param args
 * @param callback
 */
exports.upd_other = function(params, args, callback){
    let sql1 = 'SELECT * FROM admin WHERE id = $1';//查找是否有这个用户
    let sql2 = 'UPDATE admin SET adminname = $1, role = $2, status = $3, "desc" = $4, headurl = $5 WHERE id = $6';//编辑用户（带状态）
    let sql3 = 'UPDATE admin SET adminname = $1, role = $2, "desc" = $3, headurl = $4 WHERE id = $5';//编辑用户（不带状态）
    let params1 = [
        args.id
    ];
    pg.query(sql1, params1, function(err, result){//查用户
        if(err){
            callback (err, null);//报错
        }else if(result.rowCount == 0){
            callback (err, 'null');//没有这个用户
        }else if(result.rows[0].status == '3'||args.status == '3'){//用户未激活
            pg.query(sql3, params, function(err, result){//编辑用户
                if(err){
                    callback (err, null);//报错
                }else if(result.rowCount == 0){
                    callback (err, 'fail');//失败
                }else{
                    callback (err, result);//成功
                }
            })
        }else{
            pg.query(sql2, params, function(err, result){//编辑用户
                if(err){
                    callback (err, null);//报错
                }else if(result.rowCount == 0){
                    callback (err, 'fail');//失败
                }else{
                    callback (err, result);//成功
                }
            })
        }
    })

};
/**
 *忘记密码
 * @param params//数组，传的条件
 * @param new_user传的
 * @param callback
 */
const lost_password_sql1 = 'SELECT id FROM admin WHERE mobile = $1';//有没有这个用户
const lost_password_sql2 = 'UPDATE admin SET password=$1 WHERE mobile=$2';//修改密码



exports.lost_password = function(params, args, callback) {
    const lost_password_params1 = [args.mobile];
    pg.query(lost_password_sql1, lost_password_params1, function (err, result) {//执行查询操作
        if (err) {
            return callback(err, null);
        }
        else if(result.rowCount == 0) {//没有这个人
            return  callback(err,null);
        }else {
            pg.query(lost_password_sql2,params,function(err,result){//执行修改操作
                if(err){
                    return callback(err, null);
                } else{
                    return  callback(err,result);//执行过未报错
                }
            });
        }
    });
};
/**
 * 后台自己详情
 * @param params
 * @param callback
 */
const info_sql = 'SELECT id, adminname, mobile, role, email, status, "desc", headurl FROM admin WHERE id = $1';//根据id查找用户
exports.info = function(params, callback){
    pg.query(info_sql, params, function(err, result){//执行查找操作
        if(err){
            callback (err, null);//报错
        }else {
            callback (err, result);//返回信息
        }
    })
};
/**
 * 编辑个人信息
 * @param params
 * @param callback
 */
const upd_mysql1 = 'SELECT * FROM admin WHERE mobile = $1 and id != $2';//查找手机号重复
const upd_mysql2 = 'SELECT * FROM admin WHERE email = $1 and id != $2';//查找邮箱号重复
const upd_mysql = 'UPDATE admin SET adminname = $1, mobile = $2, email = $3, "desc" = $4, headurl = $5 WHERE id = $6';//编辑用户信息
exports.upd_admin = function(params, callback){
    pg.query(upd_mysql1, [params[1],params[5]], function(err, result){//执行sql语句，查找手机号重复
        if(err){
            callback (err, null);//报错
        }else if(result.rowCount > 0){//手机号重复
            callback (err, 'exit_mobile');
        }else {
            pg.query(upd_mysql2, [params[2],params[5]], function(err, result){//执行sql语句，查找邮箱重复
                if(err){
                    callback (err, null);//报错
                }else if(result.rowCount > 0){//失败
                    callback (err, 'exit_email');
                }else {
                    pg.query(upd_mysql, params, function(err, result){//执行sql语句,编辑用户信息
                        if(err){
                            callback (err, null);//报错
                        }else if(result.rowCount == 0){//失败
                            callback (err, 'fail');
                        }else {
                            callback (err, result);//成功
                        }
                    })
                }
            })
        }
    })
};
/**
 *批量删除系统人员信息
 */
exports.remove = function(args, callback){
    let ids = args.ids;//ids 是数组
    let theids = "'"+ids.join("','")+"'";//将数组ids整理成字符串
    const remove_sql1 = 'DELETE FROM admin WHERE id IN ('+theids+')';//删除id在theids的系统人员数据
    const remove_sql2 = 'SELECT id FROM admin WHERE id IN ('+theids+')';//查询id在theids的系统人员数据
    const remove_sql3 = 'DELETE FROM systemlogs WHERE adminid IN ('+theids+')';//删除系统人员id在theids的图片数据
    const remove_sql4 = 'SELECT id FROM systemlogs WHERE adminid IN ('+theids+')';//查询tid在theids的图片数据
    pg.query(remove_sql2, [], function(err,result){//执行查询操作
        if(err){
            callback (err,null);
        }else if(result.rowCount == 0) {//系统人员不存在
            callback (err,null);
        }else{
            pg.connect(function (err, client, done) {
                client.query(sqlStart, function () {
                    client.query(remove_sql1, [], function (err, result) {//查作者
                        if (err) {
                            log.error(err);
                            client.query(sqlRollback, function (errRollback) {
                                if (errRollback) {
                                    log.error('删除系统人员报错');
                                }
                                done();
                                callback(err, null);
                            })
                        } else if (result.rowCount == 0) {
                            log.error('删除系统人员失败');
                            client.query(sqlRollback, function (errRollback) {
                                if (errRollback) {
                                    log.error('删除系统人员失败');
                                }
                                done();
                                return callback(err,'null');
                            })
                        } else {
                            client.query(remove_sql4, [], function (err, result) {//查系统人员
                                if (err) {
                                    log.error(err);
                                    client.query(sqlRollback, function (errRollback) {
                                        if (errRollback) {
                                            log.error('删除关联记录失败');
                                        }
                                        done();
                                        callback(err, null);
                                    })
                                } else {
                                    client.query(remove_sql3, [], function (err, result) {//删除图片
                                        if (err) {//失败
                                            log.error(err);
                                            client.query(sqlRollback, function (errRollback) {
                                                if (errRollback) {
                                                    log.error('删除系统人员品牌关联失败');
                                                }
                                                done();
                                                callback(err,null);
                                            });
                                        } else {
                                            client.query(sqlCommit, function (errCommit) {
                                                if (errCommit) {
                                                    client.query(sqlRollback, function (errRollback) {
                                                        if (errRollback) {
                                                            log.error('回滚失败');
                                                        }
                                                        done();
                                                        callback(err, null);
                                                    });
                                                } else {
                                                    done();
                                                    return callback(err, result);//删除成功
                                                }
                                            });
                                        }
                                    });
                                }
                            })
                        }
                    });
                });
            })
        };
    });

};